<?php
/**
 * 阿里短信发送
 * @author tang
 */
namespace app\common\lib;

class Redis{
    //单例模式,减少连接次数
    public $redis = "";
    
    private static $_instance = null;
    
    //单例模式
    public static function getInstance() {
        if(empty(self::$_instance)){
            self::$_instance = new self();
        }
        return self::$_instance;
            
    }
    /**
     * 初始化连接redis
     */
    public function __construct() {
        $this->redis = new \Redis();
        $redis = $this->redis->connect(config('redis.host'),config('redis.port'),config('redis.timeout'));
        if($redis == FALSE){
            throw new \Exception('redis connect error');
        }
    }
    /**
     * 存储
     * @param type $key
     * @param type $val
     * @param type $expreeTime
     * @return string
     */
    public function set($key,$val,$expreeTime = 0) {
        if(!$key){
            return '';
        }
        if(is_array($val)){
            $val = json_encode($val);
        }
        
        if(!$expreeTime){
            return $this->redis->set($key,$val);
        }else{
            return $this->redis->setex($key,$expreeTime,$val);
        }
    }
    /**
     * 查询
     * @param type $key
     * @return string
     */
    public function get($key) {
        if(!$key){
            return '';
        }
        return $this->redis->get($key);
    }
    
    public function __call($name, $arguments) {
        $paramNum = count($arguments);
        switch ($paramNum) {
            case 1:
                return $this->redis->$name($arguments[0]);

                break;
            
            case 2:
                return $this->redis->$name($arguments[0],$arguments[1]);

                break;
            default:
                return 'false paramNum';
                break;
        }
        
    }
}

